package com.ywl.study.seata.service.impl;

import com.ywl.study.seata.service.AbstractDataCheck;
import com.ywl.study.seata.service.AccountService;
import com.ywl.study.seata.util.DataSourceUtil;

import java.sql.SQLException;

public class AccountServiceImpl extends AbstractDataCheck implements AccountService {

    public static final String DB_KEY="account";

    public void reduce(String userId, int money) throws SQLException {
        String sql = "update account_tbl set money = money - " + money + " where user_id = '" + userId + "'";
        DataSourceUtil.executeUpdate(DB_KEY,sql);
    }

    public int doNegativeCheck(String field, String id) throws SQLException {
        String checkSql = "select " + field + " from account_tbl where user_id='" + id + "'";
        String result = DataSourceUtil.getSingleResult(DB_KEY, checkSql);
        return Integer.parseInt(result);
    }

    public void reset(String key, String value) throws SQLException {
        String deleteSql = "delete from account_tbl where user_id = '" + key + "'";
        String insertSql = "insert into account_tbl(user_id, money) values ('" + key + "', " + value + ")";
        DataSourceUtil.executeUpdate(DB_KEY, deleteSql);
        DataSourceUtil.executeUpdate(DB_KEY, insertSql);
    }
}
